<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="刘清政">
  <meta name="keyword" content="hexo-theme">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      python/Django框架/8-模型层-单表操作 | Justin-刘清政的博客
    
  </title>
  <link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/css/plugins/gitment.css">

  
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
    
<script src="/js/gitment.js"></script>

  
  

  
<meta name="generator" content="Hexo 4.2.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>

  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>Justin-刘清政的博客</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">主页</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">标签</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">归档</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">关于我</a>
          
        </li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">主页</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">标签</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">归档</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">关于我</a>
            
          </li>
        
      </ul>
    </div>
  </div>
</header>

    <div id="article-banner">
  <h2>python/Django框架/8-模型层-单表操作</h2>



  <p class="post-date">2020-09-24</p>
    <!-- 不蒜子统计 -->
    <span id="busuanzi_container_page_pv" style='display:none' class="">
        <i class="icon-smile icon"></i> 阅读数：<span id="busuanzi_value_page_pv"></span>次
    </span>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><h2 id="一-ORM简介"><a href="#一-ORM简介" class="headerlink" title="一 ORM简介"></a>一 ORM简介</h2><p>查询数据层次图解：如果操作mysql，ORM是在pymysq之上又进行了一层封装</p>
<img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gj1wrzhtrsj30jk0fiq4u.jpg" alt="image-20200924181833097" style="zoom:50%;" />



<ul>
<li>MVC或者MTV框架中包括一个重要的部分，就是ORM，它实现了数据模型与数据库的解耦，即数据模型的设计不需要依赖于特定的数据库，通过简单的配置就可以轻松更换数据库，这极大的减轻了开发人员的工作量，不需要面对因数据库变更而导致的无效劳动</li>
<li>ORM是“对象-关系-映射”的简称。</li>
</ul>
<p><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gj1wsfg8wkj314e0i24bb.jpg" alt="image-20200924181858413"></p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#sql中的表                                                      </span></span><br><span class="line"></span><br><span class="line"> <span class="comment">#创建表:</span></span><br><span class="line">     CREATE TABLE employee(                                     </span><br><span class="line">                id INT PRIMARY KEY auto_increment ,                    </span><br><span class="line">                name VARCHAR (<span class="number">20</span>),                                      </span><br><span class="line">                gender BIT default <span class="number">1</span>,                                  </span><br><span class="line">                birthday DATA ,                                         </span><br><span class="line">                department VARCHAR (<span class="number">20</span>),                                </span><br><span class="line">                salary DECIMAL (<span class="number">8</span>,<span class="number">2</span>) unsigned,                          </span><br><span class="line">              );</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="comment">#sql中的表纪录                                                  </span></span><br><span class="line"></span><br><span class="line">  <span class="comment">#添加一条表纪录:                                                          </span></span><br><span class="line">      INSERT employee (name,gender,birthday,salary,department)            </span><br><span class="line">             VALUES   (<span class="string">"alex"</span>,<span class="number">1</span>,<span class="string">"1985-12-12"</span>,<span class="number">8000</span>,<span class="string">"保洁部"</span>);               </span><br><span class="line"></span><br><span class="line">  <span class="comment">#查询一条表纪录:                                                           </span></span><br><span class="line">      SELECT * FROM employee WHERE age=<span class="number">24</span>;                               </span><br><span class="line"></span><br><span class="line">  <span class="comment">#更新一条表纪录:                                                           </span></span><br><span class="line">      UPDATE employee SET birthday=<span class="string">"1989-10-24"</span> WHERE id=<span class="number">1</span>;              </span><br><span class="line"></span><br><span class="line">  <span class="comment">#删除一条表纪录:                                                          </span></span><br><span class="line">      DELETE FROM employee WHERE name=<span class="string">"alex"</span>                             </span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">#python的类</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Employee</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">     id=models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">     name=models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">     gender=models.BooleanField()</span><br><span class="line">     birthday=models.DateField()</span><br><span class="line">     department=models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">     salary=models.DecimalField(max_digits=<span class="number">8</span>,decimal_places=<span class="number">2</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"> <span class="comment">#python的类对象</span></span><br><span class="line">      <span class="comment">#添加一条表纪录:</span></span><br><span class="line">          emp=Employee(name=<span class="string">"alex"</span>,gender=<span class="literal">True</span>,birthday=<span class="string">"1985-12-12"</span>,epartment=<span class="string">"保洁部"</span>)</span><br><span class="line">          emp.save()</span><br><span class="line">      <span class="comment">#查询一条表纪录:</span></span><br><span class="line">          Employee.objects.filter(age=<span class="number">24</span>)</span><br><span class="line">      <span class="comment">#更新一条表纪录:</span></span><br><span class="line">          Employee.objects.filter(id=<span class="number">1</span>).update(birthday=<span class="string">"1989-10-24"</span>)</span><br><span class="line">      <span class="comment">#删除一条表纪录:</span></span><br><span class="line">          Employee.objects.filter(name=<span class="string">"alex"</span>).delete()</span><br></pre></td></tr></table></figure>



<h2 id="二-单表操作"><a href="#二-单表操作" class="headerlink" title="二 单表操作"></a>二 单表操作</h2><h3 id="2-1-创建表"><a href="#2-1-创建表" class="headerlink" title="2.1 创建表"></a>2.1 创建表</h3><h4 id="1-创建模型"><a href="#1-创建模型" class="headerlink" title="1 创建模型"></a>1 创建模型</h4><img src="https://tva1.sinaimg.cn/large/007S8ZIlgy1gj1wt64t3tj30cy0f4t98.jpg" alt="image-20200924181936140" style="zoom:50%;" />

<p>创建名为book的app，在book下的models.py中创建模型：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Book</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">    id = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">    name = models.CharField(max_length=<span class="number">64</span>)</span><br><span class="line">    pub_data = models.DateField()</span><br><span class="line">    price = models.DecimalField(max_digits=<span class="number">5</span>, decimal_places=<span class="number">2</span>)</span><br><span class="line">    publish = models.CharField(max_length=<span class="number">12</span>)</span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__str__</span><span class="params">(self)</span>:</span></span><br><span class="line">        <span class="keyword">return</span> self.name</span><br></pre></td></tr></table></figure>

<h4 id="2-更多字段"><a href="#2-更多字段" class="headerlink" title="2 更多字段"></a>2 更多字段</h4><p>每个字段有一些特有的参数，例如，CharField需要max_length参数来指定<code>VARCHAR</code>数据库字段的大小。还有一些适用于所有字段的通用参数。 这些参数在文档中有详细定义，这里我们只简单介绍一些最常用的：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br></pre></td><td class="code"><pre><span class="line">AutoField(Field)</span><br><span class="line">    - int自增列，必须填入参数 primary_key=<span class="literal">True</span></span><br><span class="line"></span><br><span class="line">BigAutoField(AutoField)</span><br><span class="line">    - bigint自增列，必须填入参数 primary_key=<span class="literal">True</span></span><br><span class="line">    注：当model中如果没有自增列，则自动会创建一个列名为id的列</span><br><span class="line">    <span class="keyword">from</span> django.db <span class="keyword">import</span> models</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">UserInfo</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">        <span class="comment"># 自动创建一个列名为id的且为自增的整数列</span></span><br><span class="line">        username = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">    <span class="class"><span class="keyword">class</span> <span class="title">Group</span><span class="params">(models.Model)</span>:</span></span><br><span class="line">        <span class="comment"># 自定义自增列</span></span><br><span class="line">        nid = models.AutoField(primary_key=<span class="literal">True</span>)</span><br><span class="line">        name = models.CharField(max_length=<span class="number">32</span>)</span><br><span class="line">SmallIntegerField(IntegerField):</span><br><span class="line">    - 小整数 <span class="number">-32768</span> ～ <span class="number">32767</span></span><br><span class="line"></span><br><span class="line">PositiveSmallIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)</span><br><span class="line">    - 正小整数 <span class="number">0</span> ～ <span class="number">32767</span></span><br><span class="line">IntegerField(Field)</span><br><span class="line">    - 整数列(有符号的) <span class="number">-2147483648</span> ～ <span class="number">2147483647</span></span><br><span class="line"></span><br><span class="line">PositiveIntegerField(PositiveIntegerRelDbTypeMixin, IntegerField)</span><br><span class="line">    - 正整数 <span class="number">0</span> ～ <span class="number">2147483647</span></span><br><span class="line"></span><br><span class="line">BigIntegerField(IntegerField):</span><br><span class="line">    - 长整型(有符号的) <span class="number">-9223372036854775808</span> ～ <span class="number">9223372036854775807</span></span><br><span class="line"></span><br><span class="line">自定义无符号整数字段</span><br><span class="line">	<span class="class"><span class="keyword">class</span> <span class="title">UnsignedIntegerField</span><span class="params">(models.IntegerField)</span>:</span></span><br><span class="line"> 	    <span class="function"><span class="keyword">def</span> <span class="title">db_type</span><span class="params">(self, connection)</span>:</span></span><br><span class="line">	        <span class="keyword">return</span> <span class="string">'integer UNSIGNED'</span></span><br><span class="line"></span><br><span class="line">    PS: 返回值为字段在数据库中的属性，Django字段默认的值为：</span><br><span class="line">        <span class="string">'AutoField'</span>: <span class="string">'integer AUTO_INCREMENT'</span>,</span><br><span class="line">        <span class="string">'BigAutoField'</span>: <span class="string">'bigint AUTO_INCREMENT'</span>,</span><br><span class="line">        <span class="string">'BinaryField'</span>: <span class="string">'longblob'</span>,</span><br><span class="line">        <span class="string">'BooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line">        <span class="string">'CharField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">        <span class="string">'CommaSeparatedIntegerField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">        <span class="string">'DateField'</span>: <span class="string">'date'</span>,</span><br><span class="line">        <span class="string">'DateTimeField'</span>: <span class="string">'datetime'</span>,</span><br><span class="line">        <span class="string">'DecimalField'</span>: <span class="string">'numeric(%(max_digits)s, %(decimal_places)s)'</span>,</span><br><span class="line">        <span class="string">'DurationField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line">        <span class="string">'FileField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">        <span class="string">'FilePathField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">        <span class="string">'FloatField'</span>: <span class="string">'double precision'</span>,</span><br><span class="line">        <span class="string">'IntegerField'</span>: <span class="string">'integer'</span>,</span><br><span class="line">        <span class="string">'BigIntegerField'</span>: <span class="string">'bigint'</span>,</span><br><span class="line">        <span class="string">'IPAddressField'</span>: <span class="string">'char(15)'</span>,</span><br><span class="line">        <span class="string">'GenericIPAddressField'</span>: <span class="string">'char(39)'</span>,</span><br><span class="line">        <span class="string">'NullBooleanField'</span>: <span class="string">'bool'</span>,</span><br><span class="line">        <span class="string">'OneToOneField'</span>: <span class="string">'integer'</span>,</span><br><span class="line">        <span class="string">'PositiveIntegerField'</span>: <span class="string">'integer UNSIGNED'</span>,</span><br><span class="line">        <span class="string">'PositiveSmallIntegerField'</span>: <span class="string">'smallint UNSIGNED'</span>,</span><br><span class="line">        <span class="string">'SlugField'</span>: <span class="string">'varchar(%(max_length)s)'</span>,</span><br><span class="line">        <span class="string">'SmallIntegerField'</span>: <span class="string">'smallint'</span>,</span><br><span class="line">        <span class="string">'TextField'</span>: <span class="string">'longtext'</span>,</span><br><span class="line">        <span class="string">'TimeField'</span>: <span class="string">'time'</span>,</span><br><span class="line">        <span class="string">'UUIDField'</span>: <span class="string">'char(32)'</span>,</span><br><span class="line"></span><br><span class="line">BooleanField(Field)</span><br><span class="line">    - 布尔值类型</span><br><span class="line"></span><br><span class="line">NullBooleanField(Field):</span><br><span class="line">    - 可以为空的布尔值</span><br><span class="line"></span><br><span class="line">CharField(Field)</span><br><span class="line">    - 字符类型</span><br><span class="line">    - 必须提供max_length参数， max_length表示字符长度</span><br><span class="line"></span><br><span class="line">TextField(Field)</span><br><span class="line">    - 文本类型</span><br><span class="line"></span><br><span class="line">EmailField(CharField)：</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供验证机制</span><br><span class="line"></span><br><span class="line">IPAddressField(Field)</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供验证 IPV4 机制</span><br><span class="line"></span><br><span class="line">GenericIPAddressField(Field)</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供验证 Ipv4和Ipv6</span><br><span class="line">    - 参数：</span><br><span class="line">        protocol，用于指定Ipv4或Ipv6， <span class="string">'both'</span>,<span class="string">"ipv4"</span>,<span class="string">"ipv6"</span></span><br><span class="line">        unpack_ipv4， 如果指定为<span class="literal">True</span>，则输入::ffff:<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>时候，可解析为<span class="number">192.0</span><span class="number">.2</span><span class="number">.1</span>，开启刺功能，需要protocol=<span class="string">"both"</span></span><br><span class="line"></span><br><span class="line">URLField(CharField)</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供验证 URL</span><br><span class="line"></span><br><span class="line">SlugField(CharField)</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供验证支持 字母、数字、下划线、连接符（减号）</span><br><span class="line"></span><br><span class="line">CommaSeparatedIntegerField(CharField)</span><br><span class="line">    - 字符串类型，格式必须为逗号分割的数字</span><br><span class="line"></span><br><span class="line">UUIDField(Field)</span><br><span class="line">    - 字符串类型，Django Admin以及ModelForm中提供对UUID格式的验证</span><br><span class="line"></span><br><span class="line">FilePathField(Field)</span><br><span class="line">    - 字符串，Django Admin以及ModelForm中提供读取文件夹下文件的功能</span><br><span class="line">    - 参数：</span><br><span class="line">            path,                      文件夹路径</span><br><span class="line">            match=<span class="literal">None</span>,                正则匹配</span><br><span class="line">            recursive=<span class="literal">False</span>,           递归下面的文件夹</span><br><span class="line">            allow_files=<span class="literal">True</span>,          允许文件</span><br><span class="line">            allow_folders=<span class="literal">False</span>,       允许文件夹</span><br><span class="line"></span><br><span class="line">FileField(Field)</span><br><span class="line">    - 字符串，路径保存在数据库，文件上传到指定目录</span><br><span class="line">    - 参数：</span><br><span class="line">        upload_to = <span class="string">""</span>      上传文件的保存路径</span><br><span class="line">        storage = <span class="literal">None</span>      存储组件，默认django.core.files.storage.FileSystemStorage</span><br><span class="line"></span><br><span class="line">ImageField(FileField)</span><br><span class="line">    - 字符串，路径保存在数据库，文件上传到指定目录</span><br><span class="line">    - 参数：</span><br><span class="line">        upload_to = <span class="string">""</span>      上传文件的保存路径</span><br><span class="line">        storage = <span class="literal">None</span>      存储组件，默认django.core.files.storage.FileSystemStorage</span><br><span class="line">        width_field=<span class="literal">None</span>,   上传图片的高度保存的数据库字段名（字符串）</span><br><span class="line">        height_field=<span class="literal">None</span>   上传图片的宽度保存的数据库字段名（字符串）</span><br><span class="line"></span><br><span class="line">DateTimeField(DateField)</span><br><span class="line">    - 日期+时间格式 YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ]</span><br><span class="line"></span><br><span class="line">DateField(DateTimeCheckMixin, Field)</span><br><span class="line">    - 日期格式      YYYY-MM-DD</span><br><span class="line"></span><br><span class="line">TimeField(DateTimeCheckMixin, Field)</span><br><span class="line">    - 时间格式      HH:MM[:ss[.uuuuuu]]</span><br><span class="line"></span><br><span class="line">DurationField(Field)</span><br><span class="line">    - 长整数，时间间隔，数据库中按照bigint存储，ORM中获取的值为datetime.timedelta类型</span><br><span class="line"></span><br><span class="line">FloatField(Field)</span><br><span class="line">    - 浮点型</span><br><span class="line"></span><br><span class="line">DecimalField(Field)</span><br><span class="line">    - <span class="number">10</span>进制小数</span><br><span class="line">    - 参数：</span><br><span class="line">        max_digits，小数总长度</span><br><span class="line">        decimal_places，小数位长度</span><br><span class="line"></span><br><span class="line">BinaryField(Field)</span><br><span class="line">    - 二进制类型</span><br></pre></td></tr></table></figure>

<h4 id="3-更多参数"><a href="#3-更多参数" class="headerlink" title="3 更多参数"></a>3 更多参数</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">(1)null</span><br><span class="line"> </span><br><span class="line">如果为True，Django 将用NULL 来在数据库中存储空值。 默认值是 False.</span><br><span class="line"> </span><br><span class="line">(1)blank</span><br><span class="line"> </span><br><span class="line">如果为True，该字段允许不填。默认为False。</span><br><span class="line">要注意，这与 null 不同。null纯粹是数据库范畴的，而 blank 是数据验证范畴的。</span><br><span class="line">如果一个字段的blank&#x3D;True，表单的验证将允许该字段是空值。如果字段的blank&#x3D;False，该字段就是必填的。</span><br><span class="line"> </span><br><span class="line">(2)default</span><br><span class="line"> </span><br><span class="line">字段的默认值。可以是一个值或者可调用对象。如果可调用 ，每有新对象被创建它都会被调用。</span><br><span class="line"> </span><br><span class="line">(3)primary_key</span><br><span class="line"> </span><br><span class="line">如果为True，那么这个字段就是模型的主键。如果你没有指定任何一个字段的primary_key&#x3D;True，</span><br><span class="line">Django 就会自动添加一个IntegerField字段做为主键，所以除非你想覆盖默认的主键行为，</span><br><span class="line">否则没必要设置任何一个字段的primary_key&#x3D;True。</span><br><span class="line"> </span><br><span class="line">(4)unique</span><br><span class="line"> </span><br><span class="line">如果该值设置为 True, 这个数据字段的值在整张表中必须是唯一的</span><br><span class="line"> </span><br><span class="line">(5)choices</span><br><span class="line">由二元组组成的一个可迭代对象（例如，列表或元组），用来给字段提供选择项。 如果设置了choices ，默认的表单将是一个选择框而不是标准的文本框，&lt;br&gt;而且这个选择框的选项就是choices 中的选项。</span><br></pre></td></tr></table></figure>



<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">class UserInfo(models.Model):</span><br><span class="line">       nid &#x3D; models.AutoField(primary_key&#x3D;True)</span><br><span class="line">       username &#x3D; models.CharField(max_length&#x3D;32)</span><br><span class="line">       class Meta:</span><br><span class="line">           # 数据库中生成的表名称 默认 app名称 + 下划线 + 类名</span><br><span class="line">           db_table &#x3D; &quot;table_name&quot;</span><br><span class="line"></span><br><span class="line">           # 联合索引</span><br><span class="line">           index_together &#x3D; [</span><br><span class="line">               (&quot;pub_date&quot;, &quot;deadline&quot;),</span><br><span class="line">           ]</span><br><span class="line"></span><br><span class="line">           # 联合唯一索引</span><br><span class="line">           unique_together &#x3D; ((&quot;driver&quot;, &quot;restaurant&quot;),)</span><br><span class="line"></span><br><span class="line">           # admin中显示的表名称</span><br><span class="line">           verbose_name</span><br><span class="line"></span><br><span class="line">           # verbose_name加s</span><br><span class="line">           verbose_name_plural</span><br></pre></td></tr></table></figure>

<h4 id="4-settings配置"><a href="#4-settings配置" class="headerlink" title="4 settings配置"></a>4 settings配置</h4><p>若想将模型转为mysql数据库中的表，需要在settings中配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">DATABASES &#x3D; &#123;</span><br><span class="line">    &#39;default&#39;: &#123;</span><br><span class="line">        &#39;ENGINE&#39;: &#39;django.db.backends.mysql&#39;,</span><br><span class="line">        &#39;NAME&#39;: &#39;lqz&#39;,</span><br><span class="line">        &#39;USER&#39;: &#39;root&#39;,</span><br><span class="line">        &#39;PASSWORD&#39;: &#39;123456&#39;,</span><br><span class="line">        &#39;HOST&#39;: &#39;127.0.0.1&#39;,</span><br><span class="line">        &#39;PORT&#39;: 3306,</span><br><span class="line">        &#39;ATOMIC_REQUEST&#39;: True,</span><br><span class="line">        &#39;OPTIONS&#39;: &#123;</span><br><span class="line">            &quot;init_command&quot;: &quot;SET storage_engine&#x3D;MyISAM&quot;,</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#39;&#39;&#39;</span><br><span class="line">&#39;NAME&#39;:要连接的数据库，连接前需要创建好</span><br><span class="line">&#39;USER&#39;:连接数据库的用户名</span><br><span class="line">&#39;PASSWORD&#39;:连接数据库的密码</span><br><span class="line">&#39;HOST&#39;:连接主机，默认本机</span><br><span class="line">&#39;PORT&#39;:端口 默认3306</span><br><span class="line">&#39;ATOMIC_REQUEST&#39;: True,</span><br><span class="line">设置为True统一个http请求对应的所有sql都放在一个事务中执行（要么所有都成功，要么所有都失败）。</span><br><span class="line">是全局性的配置， 如果要对某个http请求放水（然后自定义事务），可以用non_atomic_requests修饰器 </span><br><span class="line">&#39;OPTIONS&#39;: &#123;</span><br><span class="line">             &quot;init_command&quot;: &quot;SET storage_engine&#x3D;MyISAM&quot;,</span><br><span class="line">            &#125;</span><br><span class="line">设置创建表的存储引擎为MyISAM，INNODB</span><br><span class="line">&#39;&#39;&#39;</span><br></pre></td></tr></table></figure>

<p><strong>注意1：</strong>NAME即数据库的名字，在mysql连接前该数据库必须已经创建，而上面的sqlite数据库下的db.sqlite3则是项目自动创建 USER和PASSWORD分别是数据库的用户名和密码。设置完后，再启动我们的Django项目前，我们需要激活我们的mysql。然后，启动项目，会报错：no module named MySQLdb  。这是因为django默认你导入的驱动是MySQLdb，可是MySQLdb 对于py3有很大问题，所以我们需要的驱动是PyMySQL 所以，我们只需要找到项目名文件下的<strong>init</strong>,在里面写入：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">import pymysql</span><br><span class="line">pymysql.install_as_MySQLdb()</span><br></pre></td></tr></table></figure>

<p>最后通过两条数据库迁移命令即可在指定的数据库中创建表 ：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">python manage.py makemigrations</span><br><span class="line">python manage.py migrate</span><br></pre></td></tr></table></figure>

<p><strong>注意2:</strong>确保配置文件中的INSTALLED_APPS中写入我们创建的app名称</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">INSTALLED_APPS &#x3D; [</span><br><span class="line">    &#39;django.contrib.admin&#39;,</span><br><span class="line">    &#39;django.contrib.auth&#39;,</span><br><span class="line">    &#39;django.contrib.contenttypes&#39;,</span><br><span class="line">    &#39;django.contrib.sessions&#39;,</span><br><span class="line">    &#39;django.contrib.messages&#39;,</span><br><span class="line">    &#39;django.contrib.staticfiles&#39;,</span><br><span class="line">    &quot;book&quot;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<p><strong>注意3:</strong>如果报错如下：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.3 or newer is required; you have 0.7.11.None</span><br></pre></td></tr></table></figure>

<p>MySQLclient目前只支持到python3.4，因此如果使用的更高版本的python，需要修改如下：</p>
<p>通过查找路径C:\Programs\Python\Python36-32\Lib\site-packages\Django-2.0-py3.6.egg\django\db\backends\mysql<br>这个路径里的文件把</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">if version &lt; (1, 3, 3):</span><br><span class="line">     raise ImproperlyConfigured(&quot;mysqlclient 1.3.3 or newer is required; you have %s&quot; % Database.__version__)</span><br></pre></td></tr></table></figure>

<p>注释掉就可以了</p>
<p><strong>注意4:</strong> 如果想打印orm转换过程中的sql，需要在settings中进行如下配置：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">LOGGING &#x3D; &#123;</span><br><span class="line">    &#39;version&#39;: 1,</span><br><span class="line">    &#39;disable_existing_loggers&#39;: False,</span><br><span class="line">    &#39;handlers&#39;: &#123;</span><br><span class="line">        &#39;console&#39;:&#123;</span><br><span class="line">            &#39;level&#39;:&#39;DEBUG&#39;,</span><br><span class="line">            &#39;class&#39;:&#39;logging.StreamHandler&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;loggers&#39;: &#123;</span><br><span class="line">        &#39;django.db.backends&#39;: &#123;</span><br><span class="line">            &#39;handlers&#39;: [&#39;console&#39;],</span><br><span class="line">            &#39;propagate&#39;: True,</span><br><span class="line">            &#39;level&#39;:&#39;DEBUG&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="5-增加，删除字段"><a href="#5-增加，删除字段" class="headerlink" title="5 增加，删除字段"></a>5 增加，删除字段</h4><p>　　删除，直接注释掉字段，执行数据库迁移命令即可</p>
<p>　　新增字段，在类里直接新增字段，直接执行数据库迁移命令会提示输入默认值，此时需要设置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">publish &#x3D; models.CharField(max_length&#x3D;12,default&#x3D;&#39;人民出版社&#39;,null&#x3D;True)</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<p>　　<strong>1 数据库迁移记录都在 app01下的migrations里</strong></p>
<p>　　<strong>2 使用showmigrations命令可以查看没有执行migrate的文件</strong></p>
<p>　　<strong>3 makemigrations是生成一个文件，migrate是将更改提交到数据量</strong></p>
<h3 id="2-2-添加表纪录"><a href="#2-2-添加表纪录" class="headerlink" title="2.2 添加表纪录"></a>2.2 添加表纪录</h3><p><strong>方式1</strong> </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"># create方法的返回值book_obj就是插入book表中的python葵花宝典这本书籍纪录对象</span><br><span class="line">book_obj&#x3D;Book.objects.create(title&#x3D;&quot;python葵花宝典&quot;,state&#x3D;True,price&#x3D;100,publish&#x3D;&quot;苹果出版社&quot;,pub_date&#x3D;&quot;2012-12-12&quot;)</span><br></pre></td></tr></table></figure>

<p><strong>方式2</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">book_obj&#x3D;Book(title&#x3D;&quot;python葵花宝典&quot;,state&#x3D;True,price&#x3D;100,publish&#x3D;&quot;苹果出版社&quot;,pub_date&#x3D;&quot;2012-12-12&quot;)</span><br><span class="line">book_obj.save()</span><br></pre></td></tr></table></figure>

<h3 id="2-3-查询表纪录"><a href="#2-3-查询表纪录" class="headerlink" title="2.3 查询表纪录"></a>2.3 查询表纪录</h3><p><strong>查询API</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">&lt;1&gt; all():                  查询所有结果</span><br><span class="line">  </span><br><span class="line">&lt;2&gt; filter(**kwargs):       它包含了与所给筛选条件相匹配的对象</span><br><span class="line">  </span><br><span class="line">&lt;3&gt; get(**kwargs):          返回与所给筛选条件相匹配的对象，返回结果有且只有一个，如果符合筛选条件的对象超过一个或者没有都会抛出错误。</span><br><span class="line">  </span><br><span class="line">&lt;4&gt; exclude(**kwargs):      它包含了与所给筛选条件不匹配的对象</span><br><span class="line"> </span><br><span class="line">&lt;5&gt; order_by(*field):       对查询结果排序(&#39;-id&#39;)</span><br><span class="line">  </span><br><span class="line">&lt;6&gt; reverse():              对查询结果反向排序</span><br><span class="line">  </span><br><span class="line">&lt;8&gt; count():                返回数据库中匹配查询(QuerySet)的对象数量。</span><br><span class="line">  </span><br><span class="line">&lt;9&gt; first():                返回第一条记录</span><br><span class="line">  </span><br><span class="line">&lt;10&gt; last():                返回最后一条记录</span><br><span class="line">  </span><br><span class="line">&lt;11&gt; exists():              如果QuerySet包含数据，就返回True，否则返回False</span><br><span class="line"> </span><br><span class="line">&lt;12&gt; values(*field):        返回一个ValueQuerySet——一个特殊的QuerySet，运行后得到的并不是一系列</span><br><span class="line">                            model的实例化对象，而是一个可迭代的字典序列</span><br><span class="line">&lt;13&gt; values_list(*field):   它与values()非常相似，它返回的是一个元组序列，values返回的是一个字典序列</span><br><span class="line"> </span><br><span class="line">&lt;14&gt; distinct():            从返回结果中剔除重复纪录</span><br></pre></td></tr></table></figure>









<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br></pre></td><td class="code"><pre><span class="line">def index(request):</span><br><span class="line">    # 添加表记录++++++++++++++++++++++++++++++++++</span><br><span class="line">    # 方式一</span><br><span class="line">    # book&#x3D;Book(name&#x3D;&#39;红楼梦&#39;,pub_data&#x3D;&#39;2015-10-12&#39;,price&#x3D;88,publish&#x3D;&#39;老男孩出版社&#39;)</span><br><span class="line">    # book.save()</span><br><span class="line">    # 方式二</span><br><span class="line">    # Book.objects.create(name&#x3D;&#39;Python红宝书&#39;,pub_data&#x3D;&#39;2010-10-12&#39;,price&#x3D;100,publish&#x3D;&#39;人民出版社&#39;)</span><br><span class="line">    # 查询表记录++++++++++++++++++++++++++++++++++</span><br><span class="line">    # QUerySet数据类型（类似于一个列表，里面放着一些对象）</span><br><span class="line">    # 1 方法的返回值是什么</span><br><span class="line">    # 2 方法的调用者</span><br><span class="line">    # (1) all方法 返回一个QuerySet对象</span><br><span class="line">    # book_list&#x3D;Book.objects.all()</span><br><span class="line">    # print(book_list[1].name)</span><br><span class="line">    # print(book_list)</span><br><span class="line">    # for obj in book_list:</span><br><span class="line">    #     print(obj.name)</span><br><span class="line">    # (2)first last：调用者是queryset对象，返回值是对象</span><br><span class="line">    # book&#x3D;Book.objects.all().first()</span><br><span class="line">    # book2&#x3D;Book.objects.all().last()</span><br><span class="line">    # print(book)</span><br><span class="line">    # print(book2)</span><br><span class="line">    # (3) filter  返回值是queryset对象(相当于where语句)</span><br><span class="line">    # 可以加多个过滤条件</span><br><span class="line">    # book&#x3D;Book.objects.filter(name&#x3D;&#39;红楼梦&#39;).first()</span><br><span class="line">    # print(book)</span><br><span class="line">    # (4)get方法 有且只有一个查询结果才有意义 返回值是一个对象</span><br><span class="line">    # book&#x3D;Book.objects.get(name&#x3D;&#39;红楼梦&#39;)</span><br><span class="line">    # print(book)</span><br><span class="line">    # 直接报错</span><br><span class="line">    # book &#x3D; Book.objects.get(name&#x3D;&#39;红楼梦eee&#39;)</span><br><span class="line">    # --------------最常用-----------------</span><br><span class="line">    # (5)exclude 除了查询之外的 返回值也是queryset</span><br><span class="line">    # ret&#x3D;Book.objects.exclude(name&#x3D;&#39;红楼梦&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # （6）order_by(默认升序，加个- 就是降序),可以多个过滤条件调用者是queryset返回值也是queryset</span><br><span class="line">    # book_list&#x3D;Book.objects.all().order_by(&#39;id&#39;)</span><br><span class="line">    # book_list&#x3D;Book.objects.all().order_by(&#39;-id&#39;,&#39;price&#39;)</span><br><span class="line">    # print(book_list)</span><br><span class="line">    # （7）count() 调用者是queryset，返回值是int</span><br><span class="line">    # ret&#x3D;Book.objects.all().count()</span><br><span class="line">    # print(ret)</span><br><span class="line">    # (8)exist()判断是是否有值，不能传参数，</span><br><span class="line">    # ret&#x3D;Book.objects.all().exists()</span><br><span class="line">    # print(ret)</span><br><span class="line">    # （9）values方法</span><br><span class="line">    # 查询所有书籍的名称(里面传的值，前提是表有这个字段)也是queryset但是里面放的是字典</span><br><span class="line">    &#39;&#39;&#39;</span><br><span class="line">    values原理</span><br><span class="line">    temp&#x3D;[]</span><br><span class="line">    for obj in Book.objects.all():</span><br><span class="line">        temp.append(&#123;&#39;name&#39;:obj.name&#125;)</span><br><span class="line">    &#39;&#39;&#39;</span><br><span class="line">    # ret&#x3D;Book.objects.all().values(&#39;name&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 不加.all()也可以,调用是queryset返回值也是queryset</span><br><span class="line">    # ret&#x3D;Book.objects.values(&#39;price&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # （10）value_list</span><br><span class="line">    # ret&#x3D;Book.objects.all().values_list(&#39;price&#39;,&#39;name&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # (11) distinct  seletc * 的时候没有意义</span><br><span class="line">    # SELECT DISTINCT name from app01_book;</span><br><span class="line">    # 没有任何意义，不要这样么用</span><br><span class="line">    # Book.objects.all().distinct()</span><br><span class="line">    # ret&#x3D;Book.objects.all().values(&#39;name&#39;).distinct()</span><br><span class="line">    # print(ret)</span><br><span class="line"></span><br><span class="line">    # 双下划线模糊查询-----------------------</span><br><span class="line">    # 查询价格大于100的书</span><br><span class="line">    # ret&#x3D;Book.objects.filter(price__gt&#x3D;100)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 查询大于50小于100的书</span><br><span class="line">    # ret&#x3D;Book.objects.filter(price__gt&#x3D;50,price__lt&#x3D;100)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 查询已红楼开头的书</span><br><span class="line">    # ret&#x3D;Book.objects.filter(name__startswith&#x3D;&#39;红楼&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 查询包含‘红’的书</span><br><span class="line">    # ret&#x3D; Book.objects.filter(name__contains&#x3D;&#39;红&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # icontains  不区分大小写</span><br><span class="line">    # 价格在50，88，100 中的</span><br><span class="line">    # ret&#x3D;Book.objects.filter(price__in&#x3D;[50,88,100])</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 出版日期在2018年的</span><br><span class="line">    # ret&#x3D;Book.objects.filter(pub_data__year&#x3D;2015,pub_data__month&#x3D;2)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 删除，修改------------------------</span><br><span class="line">    # delete：调用者可以是queryset也可以是model对象</span><br><span class="line">    # 删除价格为188的书有返回值 (1, &#123;&#39;app01.Book&#39;: 1&#125;) 删除的个数，那张表，记录数</span><br><span class="line">    # ret&#x3D;Book.objects.filter(price&#x3D;188).delete()</span><br><span class="line">    # print(ret)</span><br><span class="line">    # ret&#x3D;Book.objects.filter(price&#x3D;100).first().delete()</span><br><span class="line">    # print(ret)</span><br><span class="line"></span><br><span class="line">    # 修改 update只能queryset来调用 返回值为int</span><br><span class="line">    # ret&#x3D;Book.objects.filter(name&#x3D;&#39;红楼梦1&#39;).update(name&#x3D;&#39;红楼梦&#39;)</span><br><span class="line">    # print(ret)</span><br><span class="line">    # 报错</span><br><span class="line">    # Book.objects.filter(name&#x3D;&#39;红楼梦&#39;).first().update(name&#x3D;&#39;红楼梦1&#39;)</span><br><span class="line"></span><br><span class="line">    # ret&#x3D;Book.objects.filter(name&#x3D;&#39;红楼梦1&#39;).first()</span><br><span class="line">    # print(ret.delete())</span><br><span class="line">    # aa&#x3D;Publish.objects.filter(name&#x3D;&#39;人民出版社&#39;)</span><br><span class="line">    # print(type(aa))</span><br><span class="line">    # aa.delete()</span><br><span class="line"></span><br><span class="line">    return HttpResponse(&#39;ok&#39;)</span><br></pre></td></tr></table></figure>





<h3 id="基于双下划线的模糊查询"><a href="#基于双下划线的模糊查询" class="headerlink" title="基于双下划线的模糊查询　"></a>基于双下划线的模糊查询　</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">Book.objects.filter(price__in&#x3D;[100,200,300])</span><br><span class="line">Book.objects.filter(price__gt&#x3D;100)</span><br><span class="line">Book.objects.filter(price__lt&#x3D;100)</span><br><span class="line">Book.objects.filter(price__gte&#x3D;100)</span><br><span class="line">Book.objects.filter(price__lte&#x3D;100)</span><br><span class="line">Book.objects.filter(price__range&#x3D;[100,200])</span><br><span class="line">Book.objects.filter(title__contains&#x3D;&quot;python&quot;)</span><br><span class="line">Book.objects.filter(title__icontains&#x3D;&quot;python&quot;)</span><br><span class="line">Book.objects.filter(title__startswith&#x3D;&quot;py&quot;)</span><br><span class="line">Book.objects.filter(pub_date__year&#x3D;2012)</span><br></pre></td></tr></table></figure>

<h3 id="2-5-删除表纪录"><a href="#2-5-删除表纪录" class="headerlink" title="2.5 删除表纪录"></a>2.5 删除表纪录</h3><p>删除方法就是 delete()。它运行时立即删除对象而不返回任何值。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">model_obj.delete()</span><br></pre></td></tr></table></figure>

<p>你也可以一次性删除多个对象。每个 QuerySet 都有一个 delete() 方法，它一次性删除 QuerySet 中所有的对象。</p>
<p>例如，下面的代码将删除 pub_date 是2005年的 Entry 对象：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Entry.objects.filter(pub_date__year&#x3D;2005).delete()</span><br></pre></td></tr></table></figure>

<p>在 Django 删除对象时，会模仿 SQL 约束 ON DELETE CASCADE 的行为，换句话说，删除一个对象时也会删除与它相关联的外键对象。例如：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">b &#x3D; Blog.objects.get(pk&#x3D;1)</span><br><span class="line"># This will delete the Blog and all of its Entry objects.</span><br><span class="line">b.delete()</span><br></pre></td></tr></table></figure>

<p>要注意的是： delete() 方法是 QuerySet 上的方法，但并不适用于 Manager  本身。这是一种保护机制，是为了避免意外地调用 Entry.objects.delete() 方法导致 所有的  记录被误删除。如果你确认要删除所有的对象，那么你必须显式地调用：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Entry.objects.all().delete()</span><br></pre></td></tr></table></figure>

<p>如果不想级联删除，可以设置为:</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pubHouse &#x3D; models.ForeignKey(to&#x3D;&#39;Publisher&#39;, on_delete&#x3D;models.SET_NULL, blank&#x3D;True, null&#x3D;True)</span><br></pre></td></tr></table></figure>

<h3 id="2-6-修改表纪录"><a href="#2-6-修改表纪录" class="headerlink" title="2.6 修改表纪录"></a>2.6 修改表纪录</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Book.objects.filter(title__startswith&#x3D;&quot;py&quot;).update(price&#x3D;120</span><br></pre></td></tr></table></figure>

<p>此外，update()方法对于任何结果集（QuerySet）均有效，这意味着你可以同时更新多条记录update()方法会返回一个整型数值，表示受影响的记录条数。</p>
<h2 id="三-在Python脚本中调用Django环境"><a href="#三-在Python脚本中调用Django环境" class="headerlink" title="三 在Python脚本中调用Django环境"></a>三 在Python脚本中调用Django环境</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">import os</span><br><span class="line">if __name__ &#x3D;&#x3D; &#39;__main__&#39;:</span><br><span class="line">    os.environ.setdefault(&quot;DJANGO_SETTINGS_MODULE&quot;, &quot;untitled15.settings&quot;)</span><br><span class="line">    import django</span><br><span class="line">    django.setup()</span><br><span class="line"></span><br><span class="line">    from app01 import models</span><br><span class="line"></span><br><span class="line">    books &#x3D; models.Book.objects.all()</span><br><span class="line">    print(books)</span><br></pre></td></tr></table></figure>

<h2 id="四-Django终端打印SQL语句"><a href="#四-Django终端打印SQL语句" class="headerlink" title="四 Django终端打印SQL语句"></a>四 Django终端打印SQL语句</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">LOGGING &#x3D; &#123;</span><br><span class="line">    &#39;version&#39;: 1,</span><br><span class="line">    &#39;disable_existing_loggers&#39;: False,</span><br><span class="line">    &#39;handlers&#39;: &#123;</span><br><span class="line">        &#39;console&#39;:&#123;</span><br><span class="line">            &#39;level&#39;:&#39;DEBUG&#39;,</span><br><span class="line">            &#39;class&#39;:&#39;logging.StreamHandler&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;,</span><br><span class="line">    &#39;loggers&#39;: &#123;</span><br><span class="line">        &#39;django.db.backends&#39;: &#123;</span><br><span class="line">            &#39;handlers&#39;: [&#39;console&#39;],</span><br><span class="line">            &#39;propagate&#39;: True,</span><br><span class="line">            &#39;level&#39;:&#39;DEBUG&#39;,</span><br><span class="line">        &#125;,</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="章节作业"><a href="#章节作业" class="headerlink" title="章节作业"></a>章节作业</h2><h3 id="1-图书管理系统"><a href="#1-图书管理系统" class="headerlink" title="1 图书管理系统"></a>1 图书管理系统</h3><p>实现功能：book单表的增删改查</p>
<h3 id="2-查询操作练习"><a href="#2-查询操作练习" class="headerlink" title="2 查询操作练习"></a>2 查询操作练习</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">1 查询老男孩出版社出版过的价格大于200的书籍</span><br><span class="line">2 查询2017年8月出版的所有以py开头的书籍名称 </span><br><span class="line">3 查询价格为50,100或者150的所有书籍名称及其出版社名称</span><br><span class="line">4 查询价格在100到200之间的所有书籍名称及其价格</span><br><span class="line">5 查询所有人民出版社出版的书籍的价格（从高到低排序，去重）</span><br></pre></td></tr></table></figure>

</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/python/Django%E6%A1%86%E6%9E%B6/5-%E8%B7%AF%E7%94%B1%E6%8E%A7%E5%88%B6/">
        <span class="nav-arrow">← </span>
        
          python/Django框架/5-路由控制
        
      </a>
    
    
      <a class="nav-right" href="/python/Django%E6%A1%86%E6%9E%B6/15-Django%E9%AB%98%E7%BA%A7%E4%B9%8B-cookie%E4%B8%8Esession/">
        
          python/Django框架/15-Django高级之-cookie与session
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">点击上方按钮,请我喝杯咖啡！</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- Gitment START -->
      <div id="comments"></div>
      <!-- Gitment END -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
  <!-- 不蒜子统计 -->
    <strong class="toc-title">目录</strong>
    
      <ol class="toc-nav"><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#一-ORM简介"><span class="toc-nav-text">一 ORM简介</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#二-单表操作"><span class="toc-nav-text">二 单表操作</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-1-创建表"><span class="toc-nav-text">2.1 创建表</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#1-创建模型"><span class="toc-nav-text">1 创建模型</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#2-更多字段"><span class="toc-nav-text">2 更多字段</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#3-更多参数"><span class="toc-nav-text">3 更多参数</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#4-settings配置"><span class="toc-nav-text">4 settings配置</span></a></li><li class="toc-nav-item toc-nav-level-4"><a class="toc-nav-link" href="#5-增加，删除字段"><span class="toc-nav-text">5 增加，删除字段</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-2-添加表纪录"><span class="toc-nav-text">2.2 添加表纪录</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-3-查询表纪录"><span class="toc-nav-text">2.3 查询表纪录</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#基于双下划线的模糊查询"><span class="toc-nav-text">基于双下划线的模糊查询　</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-5-删除表纪录"><span class="toc-nav-text">2.5 删除表纪录</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-6-修改表纪录"><span class="toc-nav-text">2.6 修改表纪录</span></a></li></ol></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#三-在Python脚本中调用Django环境"><span class="toc-nav-text">三 在Python脚本中调用Django环境</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#四-Django终端打印SQL语句"><span class="toc-nav-text">四 Django终端打印SQL语句</span></a></li><li class="toc-nav-item toc-nav-level-2"><a class="toc-nav-link" href="#章节作业"><span class="toc-nav-text">章节作业</span></a><ol class="toc-nav-child"><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#1-图书管理系统"><span class="toc-nav-text">1 图书管理系统</span></a></li><li class="toc-nav-item toc-nav-level-3"><a class="toc-nav-link" href="#2-查询操作练习"><span class="toc-nav-text">2 查询操作练习</span></a></li></ol></li></ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'http://www.liuqingzheng.top/python/Django框架/8-模型层-单表操作/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', 'http://file.muyutech.com/error-img.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== 'http://file.muyutech.com/error-img.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>



  <script>
    var gitmentConfig = "liuqingzheng";
    if (gitmentConfig !== 'undefined') {
      var gitment = new Gitment({
        id: "python/Django框架/8-模型层-单表操作",
        owner: "liuqingzheng",
        repo: "FuckBlog",
        oauth: {
          client_id: "32a4076431cf39d0ecea",
          client_secret: "94484bd79b3346a949acb2fda3c8a76ce16990c6"
        },
        theme: {
          render(state, instance) {
            const container = document.createElement('div')
            container.lang = "en-US"
            container.className = 'gitment-container gitment-root-container'
            container.appendChild(instance.renderHeader(state, instance))
            container.appendChild(instance.renderEditor(state, instance))
            container.appendChild(instance.renderComments(state, instance))
            container.appendChild(instance.renderFooter(state, instance))
            return container;
          }
        }
      })
      gitment.render(document.getElementById('comments'))
    }
  </script>




    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
<!-- 不蒜子统计 -->
<span id="busuanzi_container_site_pv">
     本站总访问量<span id="busuanzi_value_site_pv"></span>次
</span>
<span class="post-meta-divider">|</span>
<span id="busuanzi_container_site_uv" style='display:none'>
     本站访客数<span id="busuanzi_value_site_uv"></span>人
</span>
<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>



  <p class="copyright">
    &copy; 2021 | Proudly powered by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank">小猿取经</a>
    <br>
    Theme by <a href="https://www.cnblogs.com/xiaoyuanqujing" target="_blank" rel="noopener">小猿取经</a>
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("//cdnjs.cloudflare.com/ajax/libs/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>





<!-- Baidu Tongji -->

<script>
    var _baId = 'c5fd96eee1193585be191f318c3fa725';
    // Originial
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?" + _baId;
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
</script>


<script src="/js/script.js"></script>


<script src="/js/search.js"></script>


<script src="/js/load.js"></script>



  <span class="local-search local-search-google local-search-plugin" style="right: 50px;top: 70px;;position:absolute;z-index:2;">
      <input type="search" placeholder="站内搜索" id="local-search-input" class="local-search-input-cls" style="">
      <div id="local-search-result" class="local-search-result-cls"></div>
  </span>


  </body>
</html>